package org.szy.core.common.listener;

import cn.hutool.json.JSONUtil;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.event.EventListener;
import org.noear.solon.core.handle.Context;
import org.noear.solon.validation.ValidatorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.szy.core.common.entity.R;
import org.szy.core.common.enums.ExceptionEnum;
import org.szy.core.common.exception.BaseException;

/**
 * 全局异常监听器
 *
 * @author 孙志阳
 * @date 2022-08-20
 * @since 1.0.0
 **/
@Component
public class GlobalExceptionListener implements EventListener<Throwable> {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionListener.class);

    @Override
    public void onEvent(Throwable e) {
        log.error("进入GlobalExceptionListener");
        Context ctx = Context.current();
        //或者记录到日志系统，或者别的处理
        if (e instanceof BaseException) {
            baseException((BaseException) e, ctx);
        } else if (e instanceof ValidatorException) {
            ctx.outputAsJson(JSONUtil.toJsonStr(R.fail(e.getMessage())));
        } else {
            e.printStackTrace();
            ctx.outputAsJson(JSONUtil.toJsonStr(R.fail(e.getMessage())));
        }

    }

    /**
     * 自定义异常处理
     *
     * @param e   异常类
     * @param ctx 上下文
     */
    public void baseException(BaseException e, Context ctx) {
        log.error(e.getMessage());
        int code = e.getCode() == null ? ExceptionEnum.ERROR500.getCode() : e.getCode();
        ctx.outputAsJson(JSONUtil.toJsonStr(R.fail(code, e.getMessage())));
    }


}
